/*
 * ©2023 JOY-HUBS.COM
 */

package com.joyhubs.base.util;

import java.util.Optional;

import lombok.extern.slf4j.Slf4j;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json support
 */
@Slf4j
public class JsonUtil {
    
    /**
     * global jackson json object mapper with default configuration
     */
    public static final ObjectMapper GLOBAL_OBJECT_MAPPER = new ObjectMapper();
    
    /**
     * convert object to json string
     *
     * @param obj
     * @return
     */
    public static Optional<String> toJson(Object obj) {
        try {
            String json = GLOBAL_OBJECT_MAPPER.writeValueAsString(obj);
            return Optional.ofNullable(json);
        } catch (JsonProcessingException e) {
            log.error("json format error", e);
            return Optional.empty();
        }
    }
    
}
